<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '#' }">
                运动会基本信息设置
            </el-breadcrumb-item>
            <el-breadcrumb-item>
                <a href="#">设置记录内容</a>
            </el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="re-card">
            <el-row>
                <el-col :span="3">
                    <div>
                        <el-form>
                            <el-form-item label="组别：">
                                <el-select v-model="grgroup">
                                    <el-option v-for="(item, index) in selgroup" :key="index + 1" :label="item.name"
                                        :value="item.grid"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-col>
                <el-col class="addlebtn" :span="4">
                    <div>
                        <el-button type="warning" @click="augmentadd">新增</el-button>
                        <el-button type="danger" @click="delectAlltableData(grgroup)">全部删除</el-button>
                    </div>
                </el-col>
                <el-col :span="3" class="cosp15">
                    <div>
                        <el-button type="primary" @click="leadFileVisible = true">导入</el-button>
                        <el-button type="primary" @click="exportExcel(grgroup)">导出</el-button>
                    </div>
                </el-col>
            </el-row>

            <el-table :data="infoData" border stripe>
                <el-table-column label="编号" type="index" width="60">
                </el-table-column>
                <el-table-column prop="msidName" label="项目">
                </el-table-column>
                <el-table-column prop="rmark" label="标识">
                </el-table-column>
                <el-table-column prop="mrectimeStr" label="男子记录">
                </el-table-column>
                <el-table-column prop="frectimeStr" label="女子记录">
                </el-table-column>
                <el-table-column label="备注">
                    <template #default="scope">
                        {{ scope.row.mname }},{{ scope.row.fname }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" @click="showeditdialog(scope.row)">修改</el-button>
                        <el-button type="danger" @click="redelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-dialog title="导入" v-model="leadFileVisible" width="20%" draggable>
                <input type="file" class="dialog-inp" @change="handleFileUpload">
                <div slot="footer" class="dialog-footer">
                    <el-button @click="leadFileVisible = false">取 消</el-button>
                    <el-button type="primary" @click="uploadFile">确 定</el-button>
                </div>
            </el-dialog>


            <!-- 修改页面 -->
            <el-dialog title="记录内容修改" v-model="editdialogVisible" width="50%" draggable :before-close="handleClose">
                <el-form :model="editfrom" label-width="120">
                    <el-form-item label="项目：">
                        <el-select v-model="editfrom.msid">
                            <el-option v-for="(item, index) in selectItem" :key="index + 1" :label="item.cname"
                                :value="item.msid"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="记录标识：">
                        <el-select v-model="editfrom.rtypeName">
                            <el-option v-for="item in records" :key="item.rnkey"
                                :label="item.rtype + '--' + item.recmark" :value="item.rtype"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="男子记录：">
                                <el-input v-model="editfrom.mrectimeStr"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="男子姓名：">
                                <el-input v-model="editfrom.mname"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="登记时间：">
                                <el-date-picker v-model="editfrom.mregdate" value-format="YYYY-MM-DD" type="date"
                                    placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="女子记录：">
                                <el-input v-model="editfrom.frectimeStr"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="女子姓名：">
                                <el-input v-model="editfrom.fname"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="登记时间：">
                                <el-date-picker v-model="editfrom.fregdate" value-format="YYYY-MM-DD" type="date"
                                    placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancelEdit">取 消</el-button>
                    <el-button type="primary" @click="editRecinfo">确 定</el-button>
                </div>
            </el-dialog>

            <!-- 添加页面 -->
            <el-dialog title="新增记录" v-model="adddialogVisible" width="50%" draggable :before-close="addleClose">
                <el-form :model="addfrom" label-width="120" :rules="rules" ref="addForm">
                    <el-form-item prop="msid" label="项目：">
                        <el-select v-model="addfrom.msid">
                            <el-option v-for="(item, index) in selectItem" :key="index + 1" :label="item.cname"
                                :value="item.msid"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="rtypeName" label="记录标识：">
                        <el-select v-model="addfrom.rtypeName">
                            <el-option v-for="item in records" :key="item.rnkey"
                                :label="item.rtype + '--' + item.recmark" :value="item.rtype"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="mrectimeStr" label="男子记录：">
                        <CustomInput ref="customInput"></CustomInput>
                        <span class="hint">(正确格式:00:00:00.000)</span>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="男子姓名：">
                                <el-input v-model="addfrom.mname"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item prop="mregdate" label="登记时间：">
                                <el-date-picker v-model="addfrom.mregdate" value-format="YYYY-MM-DD" type="date"
                                    placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item prop="frectimeStr" label="女子记录：">
                        <CustomInput ref="customInput2"></CustomInput>
                        <span class="hint">(正确格式:00:00:00.000)</span>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="女子姓名：">
                                <el-input v-model="addfrom.fname"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item prop="fregdate" label="登记时间：">
                                <el-date-picker v-model="addfrom.fregdate" value-format="YYYY-MM-DD" type="date"
                                    placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addleClose">取 消</el-button>
                    <el-button type="primary" @click="addpc">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import XLSX from 'xlsx'
import CustomInput from '../components/CustomInput.vue'
export default {
    components: {
        XLSX,
        CustomInput
    },
    data() {
        return {
            selgroup: [],
            grgroup: 1,
            records: [],
            selectItem: [],
            infoData: [],
            editdialogVisible: false,
            editfrom: {},
            adddialogVisible: false,
            addfrom: {
                grid: null,
                msid: null,
                rtypeName: '',
                mrectime: null,
                mname: '',
                mregdate: null,
                mrectimeStr: '',
                frectime: null,
                frectimeStr: '',
                fname: '',
                fregdate: null,
            },
            initialForm: {},
            leadFileVisible: false,
            formData: null,
            rules: {
                msid: [
                    { required: true, message: '请选择项目', trigger: 'change' },
                ],
                rtypeName: [
                    { required: true, message: '请选择记录标识', trigger: 'change' },
                ],
                mrectimeStr: [
                    { required: true, message: '请设置男子记录(填写九位数字即可)', trigger: 'blur' },
                ],
                frectimeStr: [
                    { required: true, message: '请设置女子记录(填写九位数字即可)', trigger: 'blur' },
                ],
                mregdate: [
                    { required: true, message: '请输入男子登记时间', trigger: 'blur' },
                ],
                fregdate: [
                    { required: true, message: '请输入女子登记时间', trigger: 'blur' },
                ],
            }
        }
    },
    created() {
        this.initialForm = { ...this.addfrom }
        this.getGroupinfoList();
        this.getRecinfoList(this.grgroup);
        this.getRecordsinfoList(this.grgroup);
        this.postIteminfoList();
    },
    methods: {
        // 查询
        async getGroupinfoList() {
            const result = await this.$http.post(this.BACKEND_URL + '/match/getGroupmsg');
            if (result.data.code == 0) {
                this.selgroup = result.data.data
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        async getRecinfoList(grid) { // 数据
            try {
                const result = await this.$http.get(this.BACKEND_URL + '/rec/getmsg', { params: { grid: grid } });
                if (result.data.code == 0) {
                    this.infoData = result.data.data
                } else if (result.data.code == 500) {
                    console.log(result.data.msg)
                }
            } catch (error) {
                if (error === undefined) {
                    this.$message.error('连接错误-获取数据失败');
                }
            }
        },
        async getRecordsinfoList(grid) {
            const result = await this.$http.get(this.BACKEND_URL + '/Cname/getmsgByGrid', { params: { grid: grid } });
            if (result.data.code == 0) {
                this.records = result.data.data
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        async postIteminfoList() {
            const result = await this.$http.post(this.BACKEND_URL + '/contest/getnoQuanNengMsg');
            if (result.data.code == 0) {
                this.selectItem = result.data.data
            } else if (result.data.code == 500) {
                console.log(result.data.msg)
            }
        },
        // 转化记录时间格式
        formatTime(value) {
            const [hours, minutes, seconds] = value.split(':');
            const milliseconds = (parseInt(hours, 10) * 3600 + parseInt(minutes, 10) * 60 + parseFloat(seconds)) * 1000;
            return milliseconds
        },
        // 获取单个数据信息
        async showeditdialog(info) {
            this.editdialogVisible = true
            this.editfrom = info
        },
        //修改
        async editRecinfo() {
            this.editfrom.frectime = this.formatTime(this.editfrom.frectimeStr)
            this.editfrom.mrectime = this.formatTime(this.editfrom.mrectimeStr)
            const result = await this.$http.post(this.BACKEND_URL + '/rec/updatemsg', this.editfrom)
            if (result.data.code == 0) {
                this.editdialogVisible = false
                this.getRecinfoList(this.grgroup);
                this.$message.success('修改成功')
            } else if (result.data.code == 500) {
                this.getRecinfoList(this.grgroup);
                this.$message.error(result.data.msg)
            }
        },
        cancelEdit() {
            this.editdialogVisible = false
            this.getRecinfoList(this.grgroup);
        },
        handleClose(done) {
            this.getRecinfoList(this.grgroup)
            done()
        },
        // 删除单条数据
        redelete(e) {
            this.$confirm('此操作将删除改条数据，是否继续', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(async () => {
                const result = await this.$http.post(this.BACKEND_URL + '/rec/deletemsg', e)
                if (result.data.code === 0) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getRecinfoList(this.grgroup);
                } else if (result.data.code == 500) {
                    this.$message.error(result.data.msg)
                }
            }).catch(() => {
            });
        },
        augmentadd() {
            this.adddialogVisible = true
        },
        // 新增数据
        async addpc() {
            this.addfrom.mrectimeStr = this.$refs.customInput.acquireValue();
            this.addfrom.frectimeStr = this.$refs.customInput2.acquireValue();
            this.$refs.addForm.validate(async (valid) => {
                if (valid) {
                    this.addfrom.frectime = this.formatTime(this.addfrom.frectimeStr)
                    this.addfrom.mrectime = this.formatTime(this.addfrom.mrectimeStr)
                    this.addfrom.grid = this.grgroup
                    const result = await this.$http.post(this.BACKEND_URL + '/rec/insertmsg', this.addfrom)
                    if (result.data.code == 0) {
                        this.adddialogVisible = false
                        this.getRecinfoList(this.grgroup)
                        this.$message.success('添加成功')
                        this.addfrom = { ...this.initialForm }
                        this.$refs.customInput.acquireValue(true);
                        this.$refs.customInput2.acquireValue(true);
                    } else if (result.data.code == 500) {
                        this.addfrom = { ...this.initialForm }
                        this.$refs.customInput.acquireValue(true);
                        this.$refs.customInput2.acquireValue(true);
                        this.$message.error(result.data.msg)
                    }
                } else {
                    this.$message.error('请填写必要信息');
                }
            });
        },
        addleClose() {
            this.adddialogVisible = false
            this.addfrom = { ...this.initialForm }
            this.$refs.customInput.acquireValue(true);
            this.$refs.customInput2.acquireValue(true);
        },
        // 删除全部数据
        async delectAlltableData(val) {
            this.$confirm('确定要删除全部数据吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(async () => {
                const result = await this.$http.get(this.BACKEND_URL + '/rec/deleteAll', { params: { grid: val } })
                if (result.data.code == 0) {
                    this.getRecinfoList(this.grgroup)
                    this.$message({
                        type: 'success',
                        message: '删除完成!'
                    });
                } else if (result.data.code == 500) {
                    console.log(result.data.msg)
                }
            }).catch(() => {
            });
        },
        // 导出
        async exportExcel(val) {
            try {
                const response = await this.$http.get(this.BACKEND_URL + '/rec/export', {
                    params: { grid: val },
                    responseType: 'blob',
                });

                let downloadUrl = window.URL.createObjectURL(new Blob([response.data]));

                const link = document.createElement('a');
                link.href = downloadUrl;
                link.setAttribute('download', '记录表S.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } catch (error) {
                console.error('File export failed:', error);
            }
        },
        // 导入
        handleFileUpload(e) {
            let file = e.target.files[0]
            this.formData = new FormData()
            this.formData.append('file', file);
        },
        async uploadFile() {
            const result = await this.$http.post(this.BACKEND_URL + '/rec/excel', this.formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            if (result.data.code == 0) {
                this.leadFileVisible = false
                this.getRecinfoList(this.grgroup)
                this.$message({
                    type: 'success',
                    message: '导入成功!'
                });
            } else {
                this.$message({
                    type: 'error',
                    message: '导入失败!'
                });
                console.log(result.data.msg)
            }
        }
    },
    watch: {
        grgroup(newGroupName, oldGroupName) {
            if (newGroupName !== oldGroupName) {
                this.getRecinfoList(newGroupName);
                this.getRecordsinfoList(newGroupName);
            }
        },
        'editfrom.rtypeName': function (newVal) {
            const selectedRecord = this.records.find(record => record.rtype === newVal);
            if (selectedRecord) {
                this.editfrom.rtypeName = selectedRecord.rtype;
                this.editfrom.rmark = selectedRecord.recmark;
            }
        },
        'addfrom.rtypeName': function (newVal) {
            const selectedRecord = this.records.find(record => record.rtype === newVal);
            if (selectedRecord) {
                this.addfrom.rtypeName = selectedRecord.rtype;
                this.addfrom.rmark = selectedRecord.recmark;
            }
        }
    },
}
</script>

<style lang="less" scoped>
.re-card {
    margin-top: 15px;
}


.dialog-inp {
    border: 1px solid #ccc;
}

.dialog-footer {
    margin-top: 15px;
}

.addlebtn {
    text-align: left;
    margin-left: 15px;
}

.cosp15 {
    margin-left: auto;
}

.btn_rt {
    margin-left: 10px;
    display: flex;
}
.hint{
    font-size: 12px; 
    color: red; 
    margin-left: 5px;
}
@media (max-width: 1489px) {
    :deep(.el-col-3) {
        min-width: 150px;
    }

    :deep(.el-col-4) {
        min-width: 165px;
    }
}
</style>